package com.fj.netty.rpc.protocol;

import com.fj.netty.rpc.message.Message;
import com.fj.netty.rpc.serializer.Algorithm;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;

import java.util.List;

/**
 * @author fj
 * @date 2024/1/17 17:23
 */
public class RpcMessageCodec extends ByteToMessageCodec<Message> {
    private final static byte[] magic = new byte[]{1,2,3,4};
    private static final byte version = 1;
    @Override
    protected void encode(ChannelHandlerContext ctx, Message msg, ByteBuf out) throws Exception {
        out.writeBytes(magic);
        out.writeByte(version);
        out.writeByte(Algorithm.JSON.ordinal());
        out.writeByte(msg.getMessageType());
        out.writeInt(msg.getSequenceId());
        out.writeByte(0xFF);//补位
        byte[] bytes = Algorithm.JSON.serialize(msg);
        out.writeInt(bytes.length);//长度
        out.writeBytes(bytes);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        int magic = in.readInt();
        byte version = in.readByte();
        byte algorithm = in.readByte();
        byte messageType = in.readByte();
        int sequenceId = in.readInt();
        in.readByte();//跳过补位字节
        int length = in.readInt();
        byte[] bytes = new byte[length];
        in.readBytes(bytes);
        Object msg = Algorithm.JSON.deserialize(Message.getMessageClass(messageType), bytes);
        out.add(msg);
    }
}
